package com.sgcc.ln.pmos.mobileapp.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.MetaDataUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;

import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshInitializer;
import com.sgcc.ln.pmos.common.interceptor.SignInterceptor;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.zhy.http.okhttp.OkHttpUtils;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.onAdaptListener;
import okhttp3.OkHttpClient;
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory;
import xyz.doikki.videoplayer.ijk.IjkPlayerFactory;
import xyz.doikki.videoplayer.player.AndroidMediaPlayerFactory;
import xyz.doikki.videoplayer.player.VideoViewConfig;
import xyz.doikki.videoplayer.player.VideoViewManager;


public class BaseAppIniter {

    private static boolean isBeforeUserAgreementInited = false;
    private static boolean isAfterUserAgreementInited = false;


    /**
     * 用户同意隐私政策之前调用，只做最基本的初始化，不能涉及任何敏感内容
     */
    public static void initBeforeUserAgreement(Application app) {
        if (isBeforeUserAgreementInited)
            return;
        isBeforeUserAgreementInited = true;
        initVideo();
        initSmartRefresh();
        initARouter(app);
        initAutoSize();
        initOkhttpUtils();
    }

    private static void initVideo(){
        VideoViewManager.setConfig(VideoViewConfig.newBuilder()
                //使用使用IjkPlayer解码
                .setPlayerFactory(IjkPlayerFactory.create())
//                使用ExoPlayer解码
                .setPlayerFactory(ExoMediaPlayerFactory.create())
                //使用MediaPlayer解码
                .setPlayerFactory(AndroidMediaPlayerFactory.create())
                .build());
    }

    private static void initOkhttpUtils() {
        try {

            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(30000, TimeUnit.MILLISECONDS)
                    .readTimeout(30000, TimeUnit.MILLISECONDS)
                    .sslSocketFactory(getSSLSocketFactory())
                    .hostnameVerifier(getHostnameVerifier())
                    .retryOnConnectionFailure(true)
                    .writeTimeout(30000, TimeUnit.MILLISECONDS);
            builder.hostnameVerifier(new AllowAllHostnameVerifier());
            builder.addInterceptor(new SignInterceptor());
            OkHttpClient okHttpClient = builder.build();
            OkHttpUtils.initClient(okHttpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

    /**
     * description 忽略https证书验证
     *`在这里插入代码片`
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }



    /**
     * 用户同意隐私政策之后调用
     */
    public static void initAfterUserAgreement(Application app) {
        if (isAfterUserAgreementInited)
            return;
        isAfterUserAgreementInited = true;
    }

    /**
     * destroy调用
     */
    public static void destroy() {
        ARouter.getInstance().destroy();
    }

    /**
     * 获取渠道
     */
    public static String getChannel() {
        return MetaDataUtils.getMetaDataInApp("channel");
    }


    /**
     * 初始化SmartRefresh
     */
    static void initSmartRefresh() {
        //设置全局默认配置（优先级最低，会被其他设置覆盖）
        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
            @SuppressLint("Range")
            @Override
            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                //开始设置全局的基本参数（可以被下面的DefaultRefreshHeaderCreator覆盖）
                layout.setHeaderHeight(60);//Header标准高度（显示下拉高度>=标准高度 触发刷新）
                layout.setFooterHeight(60);//Footer标准高度（显示上拉高度>=标准高度 触发加载）
                layout.setHeaderMaxDragRate(2);//最大显示下拉高度/Header标准高度
                layout.setFooterMaxDragRate(2);//最大显示下拉高度/Footer标准高度
                layout.setEnableOverScrollDrag(true);//是否允许越界拖动
                layout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
                layout.setEnableFooterFollowWhenNoMoreData(true);
//                layout.setEnableFooterFollowWhenLoadFinished(true);
            }
        });
        //全局设置默认的 Header
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //开始设置全局的基本参数（这里设置的属性只跟下面的MaterialHeader绑定，其他Header
                // 不会生效，能覆盖DefaultRefreshInitializer的属性和Xml设置的属性）
                layout.setEnableHeaderTranslationContent(true);
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context,
                                                     @NonNull RefreshLayout layout) {
                layout.setEnableFooterTranslationContent(true);
                layout.setEnableLoadMoreWhenContentNotFull(true);
                return new ClassicsFooter(context);
            }
        });
    }

    static void initARouter(Application app) {
        if (AppUtils.isAppDebug()) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(app);
    }


    static void initAutoSize() {
        //设置app字体不随系统字体改变
        AutoSizeConfig.getInstance()
                .setExcludeFontScale(true)
                .setOnAdaptListener(new onAdaptListener() {
                    @Override
                    public void onAdaptBefore(Object target, Activity activity) {
                        //使用以下代码, 可以解决横竖屏切换时的屏幕适配问题
                        AutoSizeConfig.getInstance().setScreenWidth(ScreenUtils.getScreenWidth());
                        AutoSizeConfig.getInstance().setScreenHeight(ScreenUtils.getScreenHeight());
                    }

                    @Override
                    public void onAdaptAfter(Object target, Activity activity) {
                    }
                })
                .getExternalAdaptManager();
    }


    public static boolean isUserAgreement() {
        return SPUtils.getInstance().getBoolean(ArguConstant.FOR_THE_FIRST_TIME, false);
    }

}
